package com.march.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.march.common.R;
import com.march.dto.SetmealDto;
import com.march.entry.Category;
import com.march.entry.Setmeal;
import com.march.service.CategoryService;
import com.march.service.SetmealDishService;
import com.march.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 套餐管理
 */

@RestController
@RequestMapping("/setmeal")
@Slf4j
public class SetmealController {

    @Autowired
    private SetmealService setmealService;

    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private CategoryService categoryService;

    @PostMapping
    public R<String> save(@RequestBody SetmealDto setmealDto){

        setmealService.savaWithDish(setmealDto);

       return R.success("添加成功");
    }
    /*
    * 套餐分页
    * */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name){

        //创建分页器
        Page<Setmeal> pageInfo = new Page<>(page,pageSize);
        Page<SetmealDto> pageDto = new Page<>();

        //查数据库
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        lqw.eq(name!=null,Setmeal::getName,name);

        setmealService.page(pageInfo,lqw);

        //拷贝分页数据到Dto
        BeanUtils.copyProperties(pageInfo,pageDto,"records");
        List<SetmealDto> setmealDtos =  pageInfo.getRecords().stream().map(item -> {
            SetmealDto setmealDto = new SetmealDto();
            //设置Dto的属性
            Category category = categoryService.getById(item.getCategoryId());
            setmealDto.setCategoryName(category.getName());
            //复制其他属性到Dto
            BeanUtils.copyProperties(item,setmealDto);
            // 返回
            return setmealDto;
        }).collect(Collectors.toList());
        // 设置分页数据
        pageDto.setRecords(setmealDtos);
        return R.success(pageDto);
    }

    /*
    * 套餐删除
    * */
    @DeleteMapping
    public R<String> del(@RequestParam List<Long> ids){

        log.info("ids:{}",ids);
        setmealService.removeWithDish(ids);
        return R.success("删除成功");

    }
}
